<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>深入理解CountDownLatch | Java并发编程</title>
    <link href="https://cdn.staticfile.org/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <link href="https://cdn.staticfile.org/tailwindcss/2.2.19/tailwind.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Noto+Serif+SC:wght@400;500;600;700&family=Noto+Sans+SC:wght@300;400;500;700&display=swap" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/mermaid@latest/dist/mermaid.min.js"></script>
    <style>
        body {
            font-family: 'Noto Sans SC', sans-serif;
            color: #333;
            line-height: 1.6;
            background-color: #f8fafc;
        }
        .code-block {
            background-color: #2d2d2d;
            color: #f8f8f2;
            border-radius: 8px;
            overflow: hidden;
        }
        .code-header {
            background-color: #1e1e1e;
            color: #9e9e9e;
            padding: 8px 16px;
            font-family: 'Consolas', monospace;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .code-content {
            padding: 16px;
            font-family: 'Consolas', monospace;
            overflow-x: auto;
        }
        .mermaid {
            margin: 20px 0;
        }
        .hover-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
        }
        .highlight {
            background-color: #fff3bf;
            padding: 2px 4px;
            border-radius: 4px;
        }
    </style>
</head>
<body class="bg-gray-50">
    <!-- Hero Section -->
    <header class="relative bg-gradient-to-r from-blue-800 to-indigo-900 text-white py-20 px-4 sm:px-6 lg:px-8">
        <div class="max-w-7xl mx-auto text-center">
            <div class="flex justify-center mb-6">
                <span class="inline-block px-3 py-1 text-sm font-semibold bg-blue-600 rounded-full">Java并发编程</span>
            </div>
            <h1 class="text-4xl md:text-5xl lg:text-6xl font-bold mb-6 font-serif">深入理解CountDownLatch</h1>
            <p class="text-xl md:text-2xl max-w-3xl mx-auto opacity-90">解密Java并发编程中的倒计时门闩机制</p>
            <div class="mt-10">
                <div class="inline-flex items-center space-x-2">
                    <i class="fas fa-clock text-blue-300"></i>
                    <span>阅读时间: 15分钟</span>
                </div>
            </div>
        </div>
        <div class="absolute bottom-0 left-0 right-0 h-16 bg-gradient-to-t from-gray-50 to-transparent"></div>
    </header>

    <!-- Main Content -->
    <main class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-12">
        <!-- Table of Contents -->
        <div class="bg-white rounded-xl shadow-md p-6 mb-12 sticky top-4 z-10">
            <h2 class="text-2xl font-bold mb-4 flex items-center">
                <i class="fas fa-list-ol text-blue-500 mr-2"></i>
                目录
            </h2>
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                <a href="#section1" class="flex items-center text-blue-600 hover:text-blue-800">
                    <i class="fas fa-book-open mr-2"></i>
                    一、CountDownLatch基础概念
                </a>
                <a href="#section2" class="flex items-center text-blue-600 hover:text-blue-800">
                    <i class="fas fa-code mr-2"></i>
                    二、CountDownLatch实战应用
                </a>
                <a href="#section3" class="flex items-center text-blue-600 hover:text-blue-800">
                    <i class="fas fa-search mr-2"></i>
                    三、源码解析
                </a>
                <a href="#section4" class="flex items-center text-blue-600 hover:text-blue-800">
                    <i class="fas fa-rocket mr-2"></i>
                    四、高级用法
                </a>
                <a href="#section5" class="flex items-center text-blue-600 hover:text-blue-800">
                    <i class="fas fa-balance-scale mr-2"></i>
                    五、与其他同步工具对比
                </a>
                <a href="#section6" class="flex items-center text-blue-600 hover:text-blue-800">
                    <i class="fas fa-user-tie mr-2"></i>
                    六、面试问题解析
                </a>
            </div>
        </div>

        <!-- Section 1: Basic Concepts -->
        <section id="section1" class="mb-16">
            <div class="flex items-center mb-8">
                <div class="w-2 h-8 bg-blue-600 mr-4 rounded-full"></div>
                <h2 class="text-3xl font-bold font-serif">一、CountDownLatch 基础概念</h2>
            </div>

            <div class="grid grid-cols-1 md:grid-cols-2 gap-8 mb-12">
                <div class="bg-white rounded-xl shadow-md p-6 hover-card transition-all duration-300">
                    <h3 class="text-xl font-bold mb-4 flex items-center">
                        <i class="fas fa-question-circle text-blue-500 mr-2"></i>
                        1.1 什么是 CountDownLatch？
                    </h3>
                    <p>CountDownLatch 是 Java 并发包（java.util.concurrent）中的一个同步工具类，它允许一个或多个线程等待一系列指定操作的完成。CountDownLatch 的核心思想是维护一个计数器，每完成一个操作，计数器减一，当计数器归零时，等待的线程被释放继续执行。</p>
                    <div class="bg-blue-50 p-4 rounded-lg mt-4">
                        <div class="flex items-start">
                            <div class="flex-shrink-0 pt-1">
                                <i class="fas fa-lightbulb text-yellow-500"></i>
                            </div>
                            <div class="ml-3">
                                <p class="text-sm text-gray-700">可以把它想象成一个倒计时器：设定一个初始值，然后等待它倒计时到零。只有倒计时结束，等待的线程才能继续执行。</p>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="bg-white rounded-xl shadow-md p-6 hover-card transition-all duration-300">
                    <h3 class="text-xl font-bold mb-4 flex items-center">
                        <i class="fas fa-cogs text-blue-500 mr-2"></i>
                        1.2 核心方法
                    </h3>
                    <ul class="space-y-2">
                        <li class="flex items-start">
                            <i class="fas fa-check-circle text-green-500 mt-1 mr-2"></i>
                            <div>
                                <span class="font-medium">countDown()</span> - 递减计数器，表示一个操作已完成
                            </div>
                        </li>
                        <li class="flex items-start">
                            <i class="fas fa-check-circle text-green-500 mt-1 mr-2"></i>
                            <div>
                                <span class="font-medium">await()</span> - 等待计数器归零，如果计数器大于0，则当前线程进入等待状态
                            </div>
                        </li>
                        <li class="flex items-start">
                            <i class="fas fa-check-circle text-green-500 mt-1 mr-2"></i>
                            <div>
                                <span class="font-medium">await(long timeout, TimeUnit unit)</span> - 带超时的等待
                            </div>
                        </li>
                        <li class="flex items-start">
                            <i class="fas fa-check-circle text-green-500 mt-1 mr-2"></i>
                            <div>
                                <span class="font-medium">getCount()</span> - 获取当前计数器的值
                            </div>
                        </li>
                    </ul>
                </div>
            </div>

            <div class="mb-12">
                <h3 class="text-xl font-bold mb-4 flex items-center">
                    <i class="fas fa-code text-blue-500 mr-2"></i>
                    1.3 基本使用示例
                </h3>
                <div class="code-block">
                    <div class="code-header">
                        <span>CountDownLatchDemo.java</span>
                        <button class="text-xs bg-blue-600 hover:bg-blue-700 text-white px-2 py-1 rounded">
                            <i class="fas fa-copy mr-1"></i>复制代码
                        </button>
                    </div>
                    <div class="code-content">
                        <pre><code class="language-java">import java.util.concurrent.CountDownLatch;

public class CountDownLatchDemo {
    public static void main(String[] args) throws InterruptedException {
        // 创建一个计数器为5的CountDownLatch
        CountDownLatch latch = new CountDownLatch(5);
        
        System.out.println("主线程开始等待所有工作线程完成...");
        
        // 创建并启动5个工作线程
        for (int i = 0; i < 5; i++) {
            final int workerId = i + 1;
            new Thread(() -> {
                try {
                    // 模拟工作线程执行任务
                    System.out.println("工作线程" + workerId + "开始执行任务");
                    Thread.sleep((long) (Math.random() * 1000));
                    System.out.println("工作线程" + workerId + "完成任务");
                    
                    // 任务完成，计数器减一
                    latch.countDown();
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }).start();
        }
        
        // 主线程等待所有工作线程完成
        latch.await();
        
        System.out.println("所有工作线程已完成，主线程继续执行");
    }
}</code></pre>
                    </div>
                </div>
            </div>

            <div class="mermaid">
                graph TD
                    A[创建CountDownLatch(5)] --> B[主线程调用await()]
                    B --> C[工作线程1调用countDown()]
                    B --> D[工作线程2调用countDown()]
                    B --> E[工作线程3调用countDown()]
                    B --> F[工作线程4调用countDown()]
                    B --> G[工作线程5调用countDown()]
                    C --> H[计数器减为4]
                    D --> I[计数器减为3]
                    E --> J[计数器减为2]
                    F --> K[计数器减为1]
                    G --> L[计数器减为0]
                    L --> M[主线程从await返回]
            </div>
        </section>

        <!-- Section 2: Practical Applications -->
        <section id="section2" class="mb-16">
            <div class="flex items-center mb-8">
                <div class="w-2 h-8 bg-blue-600 mr-4 rounded-full"></div>
                <h2 class="text-3xl font-bold font-serif">二、CountDownLatch 实战应用</h2>
            </div>

            <div class="grid grid-cols-1 md:grid-cols-3 gap-6 mb-10">
                <div class="bg-white rounded-xl shadow-md p-6 hover-card transition-all duration-300">
                    <div class="text-blue-500 text-3xl mb-4">
                        <i class="fas fa-tasks"></i>
                    </div>
                    <h3 class="text-xl font-bold mb-3">并行任务协调</h3>
                    <p class="text-gray-600 mb-4">协调多个并行任务的执行，等待所有任务完成后再继续后续操作。</p>
                    <div class="flex items-center text-sm text-blue-600">
                        <i class="fas fa-code mr-1"></i>
                        <span>系统初始化、批量处理</span>
                    </div>
                </div>

                <div class="bg-white rounded-xl shadow-md p-6 hover-card transition-all duration-300">
                    <div class="text-blue-500 text-3xl mb-4">
                        <i class="fas fa-layer-group"></i>
                    </div>
                    <h3 class="text-xl font-bold mb-3">多阶段并发处理</h3>
                    <p class="text-gray-600 mb-4">将任务分为多个阶段，每个阶段完成后才能进入下一阶段。</p>
                    <div class="flex items-center text-sm text-blue-600">
                        <i class="fas fa-code mr-1"></i>
                        <span>数据ETL处理、流水线作业</span>
                    </div>
                </div>

                <div class="bg-white rounded-xl shadow-md p-6 hover-card transition-all duration-300">
                    <div class="text-blue-500 text-3xl mb-4">
                        <i class="fas fa-chart-line"></i>
                    </div>
                    <h3 class="text-xl font-bold mb-3">并发测试</h3>
                    <p class="text-gray-600 mb-4">模拟高并发场景，测量系统在并发压力下的性能表现。</p>
                    <div class="flex items-center text-sm text-blue-600">
                        <i class="fas fa-code mr-1"></i>
                        <span>压力测试、性能基准</span>
                    </div>
                </div>
            </div>

            <div class="mb-12">
                <h3 class="text-xl font-bold mb-4 flex items-center">
                    <i class="fas fa-laptop-code text-blue-500 mr-2"></i>
                    2.1 并行任务协调示例
                </h3>
                <div class="code-block">
                    <div class="code-header">
                        <span>SystemInitializer.java</span>
                        <button class="text-xs bg-blue-600 hover:bg-blue-700 text-white px-2 py-1 rounded">
                            <i class="fas fa-copy mr-1"></i>复制代码
                        </button>
                    </div>
                    <div class="code-content">
                        <pre><code class="language-java">import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class SystemInitializer {
    public static void main(String[] args) throws InterruptedException {
        // 需要初始化的模块列表
        List&lt;String&gt; modules = Arrays.asList(
            "数据库连接模块", 
            "缓存服务模块", 
            "消息队列模块", 
            "用户认证模块", 
            "日志服务模块"
        );
        
        int moduleCount = modules.size();
        // 创建与模块数量相同的计数器
        CountDownLatch latch = new CountDownLatch(moduleCount);
        
        System.out.println("系统启动中，等待所有模块初始化...");
        
        // 创建固定大小的线程池
        ExecutorService executor = Executors.newFixedThreadPool(Math.min(moduleCount, 3));
        
        // 启动时间
        long startTime = System.currentTimeMillis();
        
        // 为每个模块创建初始化任务
        for (String module : modules) {
            executor.submit(() -> {
                try {
                    initModule(module);
                } finally {
                    // 模块初始化完成，计数器减一
                    latch.countDown();
                    System.out.println("模块 [" + module + "] 初始化完成，还剩 " + latch.getCount() + " 个模块");
                }
            });
        }
        
        // 等待所有模块初始化完成
        latch.await();
        
        // 计算总耗时
        long endTime = System.currentTimeMillis();
        System.out.println("所有模块初始化完成，系统启动成功！总耗时: " + (endTime - startTime) + "ms");
        
        // 关闭线程池
        executor.shutdown();
    }
    
    private static void initModule(String moduleName) {
        System.out.println("开始初始化模块: " + moduleName);
        try {
            // 模拟模块初始化耗时
            long sleepTime = (long) (Math.random() * 2000 + 1000);
            Thread.sleep(sleepTime);
            System.out.println("模块 [" + moduleName + "] 初始化耗时: " + sleepTime + "ms");
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            System.out.println("模块 [" + moduleName + "] 初始化被中断");
        }
    }
}</code></pre>
                    </div>
                </div>
            </div>

            <div class="mermaid">
                graph LR
                    A[开始系统启动] --> B[初始化数据库模块]
                    A --> C[初始化缓存模块]
                    A --> D[初始化消息队列]
                    A --> E[初始化认证模块]
                    A --> F[初始化日志模块]
                    B --> G[所有模块初始化完成]
                    C --> G
                    D --> G
                    E --> G
                    F --> G
                    G --> H[系统启动成功]
            </div>
        </section>

        <!-- Section 3: Source Code Analysis -->
        <section id="section3" class="mb-16">
            <div class="flex items-center mb-8">
                <div class="w-2 h-8 bg-blue-600 mr-4 rounded-full"></div>
                <h2 class="text-3xl font-bold font-serif">三、源码解析</h2>
            </div>

            <div class="bg-white rounded-xl shadow-md p-6 mb-8">
                <h3 class="text-xl font-bold mb-4 flex items-center">
                    <i class="fas fa-code-branch text-blue-500 mr-2"></i>
                    3.1 CountDownLatch 的构造与字段
                </h3>
                <p class="mb-4">CountDownLatch 内部维护了一个 Sync 实例，它是 AQS（AbstractQueuedSynchronizer）的子类：</p>
                <div class="code-block">
                    <div class="code-header">
                        <span>CountDownLatch 构造函数</span>
                        <button class="text-xs bg-blue-600 hover:bg-blue-700 text-white px-2 py-1 rounded">
                            <i class="fas fa-copy mr-1"></i>复制代码
                        </button>
                    </div>
                    <div class="code-content">
                        <pre><code class="language-java">public CountDownLatch(int count) {
    if (count &lt; 0) throw new IllegalArgumentException("count &lt; 0");
    this.sync = new Sync(count);
}

private static final class Sync extends AbstractQueuedSynchronizer {
    Sync(int count) {
        setState(count); // 使用AQS的state作为计数器
    }
    
    int getCount() {
        return getState();
    }
    
    protected int tryAcquireShared(int acquires) {
        return (getState() == 0) ? 1 : -1; // 只有计数器为0才能获取成功
    }
    
    protected boolean tryReleaseShared(int releases) {
        // CAS操作减少计数器
        for (;;) {
            int c = getState();
            if (c == 0)
                return false;
            int nextc = c-1;
            if (compareAndSetState(c, nextc))
                return nextc == 0; // 当计数器减为0时返回true
        }
    }
}</code></pre>
                    </div>
                </div>
            </div>

            <div class="grid grid-cols-1 md:grid-cols-2 gap-8 mb-12">
                <div class="bg-white rounded-xl shadow-md p-6">
                    <h3 class="text-xl font-bold mb-4 flex items-center">
                        <i class="fas fa-pause-circle text-blue-500 mr-2"></i>
                        3.2.1 await 方法实现
                    </h3>
                    <div class="code-block">
                        <div class="code-header">
                            <span>await() 方法</span>
                        </div>
                        <div class="code-content">
                            <pre><code class="language-java">public void await() throws InterruptedException {
    sync.acquireSharedInterruptibly(1);
}

// AQS中的实现
public final void acquireSharedInterruptibly(int arg)
    throws InterruptedException {
    if (Thread.interrupted())
        throw new InterruptedException();
    if (tryAcquireShared(arg) &lt; 0)
        doAcquireSharedInterruptibly(arg);
}</code></pre>
                        </div>
                    </div>
                    <p class="mt-4 text-sm text-gray-600">当计数器不为0时，调用线程会被加入到AQS的等待队列中，直到计数器归零或被中断。</p>
                </div>

                <div class="bg-white rounded-xl shadow-md p-6">
                    <h3 class="text-xl font-bold mb-4 flex items-center">
                        <i class="fas fa-arrow-down text-blue-500 mr-2"></i>
                        3.2.2 countDown 方法实现
                    </h3>
                    <div class="code-block">
                        <div class="code-header">
                            <span>countDown() 方法</span>
                        </div>
                        <div class="code-content">
                            <pre><code class="language-java">public void countDown() {
    sync.releaseShared(1);
}

// AQS中的实现
public final boolean releaseShared(int arg) {
    if (tryReleaseShared(arg)) {
        doReleaseShared(); // 唤醒等待线程
        return true;
    }
    return false;
}</code></pre>
                        </div>
                    </div>
                    <p class="mt-4 text-sm text-gray-600">计数器减一，当减至0时，唤醒所有等待的线程。</p>
                </div>
            </div>

            <div class="mermaid">
                sequenceDiagram
                    participant MainThread
                    participant WorkerThread
                    participant CountDownLatch
                    
                    MainThread->>CountDownLatch: await()
                    CountDownLatch-->>MainThread: 阻塞等待
                    
                    WorkerThread->>CountDownLatch: countDown()
                    CountDownLatch->>CountDownLatch: 计数器减1
                    
                    alt 计数器 > 0
                        CountDownLatch-->>WorkerThread: 返回
                    else 计数器 == 0
                        CountDownLatch->>MainThread: 唤醒等待线程
                    end
            </div>
        </section>

        <!-- Section 4: Advanced Usage -->
        <section id="section4" class="mb-16">
            <div class="flex items-center mb-8">
                <div class="w-2 h-8 bg-blue-600 mr-4 rounded-full"></div>
                <h2 class="text-3xl font-bold font-serif">四、CountDownLatch 的高级用法</h2>
            </div>

            <div class="grid grid-cols-1 md:grid-cols-2 gap-8 mb-12">
                <div class="bg-white rounded-xl shadow-md p-6 hover-card transition-all duration-300">
                    <h3 class="text-xl font-bold mb-4 flex items-center">
                        <i class="fas fa-hourglass-half text-blue-500 mr-2"></i>
                        4.1 带超时的等待
                    </h3>
                    <p class="mb-4">在实际应用中，我们通常不希望无限期等待，可以设置超时时间：</p>
                    <div class="code-block">
                        <div class="code-header">
                            <span>带超时的await</span>
                        </div>
                        <div class="code-content">
                            <pre><code class="language-java">boolean completed = latch.await(2, TimeUnit.SECONDS);
if (completed) {
    System.out.println("所有任务在超时前完成");
} else {
    System.out.println("等待超时，仍有" + latch.getCount() + "个任务未完成");
}</code></pre>
                        </div>
                    </div>
                </div>

                <div class="bg-white rounded-xl shadow-md p-6 hover-card transition-all duration-300">
                    <h3 class="text-xl font-bold mb-4 flex items-center">
                        <i class="fas fa-link text-blue-500 mr-2"></i>
                        4.2 结合CyclicBarrier
                    </h3>
                    <p class="mb-4">在复杂场景中可以结合使用多种同步工具：</p>
                    <div class="code-block">
                        <div class="code-header">
                            <span>组合使用示例</span>
                        </div>
                        <div class="code-content">
                            <pre><code class="language-java">CountDownLatch initLatch = new CountDownLatch(workerCount);
CyclicBarrier computeBarrier = new CyclicBarrier(workerCount);

// 等待所有线程初始化完成
initLatch.await();

// 所有线程同步开始计算
computeBarrier.await();</code></pre>
                        </div>
                    </div>
                </div>
            </div>

            <div class="bg-yellow-50 border-l-4 border-yellow-400 p-4 mb-8">
                <div class="flex">
                    <div class="flex-shrink-0">
                        <i class="fas fa-exclamation-triangle text-yellow-500"></i>
                    </div>
                    <div class="ml-3">
                        <h3 class="text-lg font-bold text-yellow-800">注意事项</h3>
                        <div class="mt-2 text-yellow-700">
                            <p class="flex items-start mb-2">
                                <i class="fas fa-check-circle text-yellow-600 mt-1 mr-2"></i>
                                <span>CountDownLatch 是一次性的，计数器归零后不能重置</span>
                            </p>
                            <p class="flex items-start mb-2">
                                <i class="fas fa-check-circle text-yellow-600 mt-1 mr-2"></i>
                                <span>确保在finally块中调用countDown()，避免线程异常导致计数器未减少</span>
                            </p>
                            <p class="flex items-start">
                                <i class="fas fa-check-circle text-yellow-600 mt-1 mr-2"></i>
                                <span>考虑使用带超时的await()方法避免死锁</span>
                            </p>
                        </div>
                    </div>
                </div>
            </div>
        </section>

        <!-- Section 5: Comparison -->
        <section id="section5" class="mb-16">
            <div class="flex items-center mb-8">
                <div class="w-2 h-8 bg-blue-600 mr-4 rounded-full"></div>
                <h2 class="text-3xl font-bold font-serif">五、CountDownLatch 与其他同步工具的对比</h2>
            </div>

            <div class="overflow-x-auto">
                <table class="min-w-full divide-y divide-gray-200 shadow-sm rounded-lg overflow-hidden">
                    <thead class="bg-gray-50">
                        <tr>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">特性</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">CountDownLatch</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">CyclicBarrier</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Semaphore</th>
                        </tr>
                    </thead>
                    <tbody class="bg-white divide-y divide-gray-200">
                        <tr>
                            <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">重用性</td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">一次性</td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">可重复使用</td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">可重复使用</td>
                        </tr>
                        <tr>
                            <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">计数方向</td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">递减</td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">先减后重置</td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">可增可减</td>
                        </tr>
                        <tr>
                            <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">主要用途</td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">等待事件</td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">线程互相等待</td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">控制资源访问</td>
                        </tr>
                        <tr>
                            <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">触发动作</td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">计数器归零</td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">所有线程到达屏障</td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">获取/释放许可</td>
                        </tr>
                    </tbody>
                </table>
            </div>

            <div class="mermaid mt-10">
                flowchart TD
                    A[选择同步工具] --> B{需要等待事件完成?}
                    B -->|是| C[CountDownLatch]
                    B -->|否| D{需要线程互相等待?}
                    D -->|是| E[CyclicBarrier]
                    D -->|否| F{需要控制资源访问?}
                    F -->|是| G[Semaphore]
                    F -->|否| H[其他机制]
            </div>
        </section>

        <!-- Section 6: Interview Questions -->
        <section id="section6" class="mb-16">
            <div class="flex items-center mb-8">
                <div class="w-2 h-8 bg-blue-600 mr-4 rounded-full"></div>
                <h2 class="text-3xl font-bold font-serif">六、面试中的 CountDownLatch 问题解析</h2>
            </div>

            <div class="space-y-6">
                <div class="bg-white rounded-xl shadow-md p-6 hover-card transition-all duration-300">
                    <h3 class="text-xl font-bold mb-3 flex items-center">
                        <i class="fas fa-question text-blue-500 mr-2"></i>
                        问题1：CountDownLatch和CyclicBarrier的主要区别是什么？
                    </h3>
                    <div class="space-y-2">
                        <p class="flex items-start">
                            <span class="inline-block bg-blue-100 text-blue-800 rounded-full w-6 h-6 flex items-center justify-center mr-2 flex-shrink-0">1</span>
                            <span><span class="font-semibold">重用性：</span>CountDownLatch是一次性的，计数器归零后不能重置；而CyclicBarrier可以通过reset()方法重置，可重复使用。</span>
                        </p>
                        <p class="flex items-start">
                            <span class="inline-block bg-blue-100 text-blue-800 rounded-full w-6 h-6 flex items-center justify-center mr-2 flex-shrink-0">2</span>
                            <span><span class="font-semibold">计数方向：</span>CountDownLatch计数器只能减少；CyclicBarrier的计数器是先减少，后自动重置。</span>
                        </p>
                        <p class="flex items-start">
                            <span class="inline-block bg-blue-100 text-blue-800 rounded-full w-6 h-6 flex items-center justify-center mr-2 flex-shrink-0">3</span>
                            <span><span class="font-semibold">使用场景：</span>CountDownLatch适用于一个或多个线程等待其他操作完成；CyclicBarrier适用于多个线程互相等待至某个状态，然后一起继续运行。</span>
                        </p>
                    </div>
                </div>

                <div class="bg-white rounded-xl shadow-md p-6 hover-card transition-all duration-300">
                    <h3 class="text-xl font-bold mb-3 flex items-center">
                        <i class="fas fa-question text-blue-500 mr-2"></i>
                        问题2：CountDownLatch的内部实现原理是什么？
                    </h3>
                    <div class="space-y-2">
                        <p class="flex items-start">
                            <span class="inline-block bg-blue-100 text-blue-800 rounded-full w-6 h-6 flex items-center justify-center mr-2 flex-shrink-0">1</span>
                            <span>CountDownLatch内部基于AQS（AbstractQueuedSynchronizer）框架实现</span>
                        </p>
                        <p class="flex items-start">
                            <span class="inline-block bg-blue-100 text-blue-800 rounded-full w-6 h-6 flex items-center justify-center mr-2 flex-shrink-0">2</span>
                            <span>使用AQS的state变量作为计数器</span>
                        </p>
                        <p class="flex items-start">
                            <span class="inline-block bg-blue-100 text-blue-800 rounded-full w-6 h-6 flex items-center justify-center mr-2 flex-shrink-0">3</span>
                            <span>await()方法调用acquireSharedInterruptibly()，当计数器不为0时线程会被阻塞</span>
                        </p>
                        <p class="flex items-start">
                            <span class="inline-block bg-blue-100 text-blue-800 rounded-full w-6 h-6 flex items-center justify-center mr-2 flex-shrink-0">4</span>
                            <span>countDown()方法调用releaseShared()，当计数器减至0时唤醒所有等待线程</span>
                        </p>
                    </div>
                </div>

                <div class="bg-white rounded-xl shadow-md p-6 hover-card transition-all duration-300">
                    <h3 class="text-xl font-bold mb-3 flex items-center">
                        <i class="fas fa-question text-blue-500 mr-2"></i>
                        问题3：实现一个高并发限流器，限制最大并发请求数为100
                    </h3>
                    <div class="code-block">
                        <div class="code-header">
                            <span>RequestLimiter.java</span>
                        </div>
                        <div class="code-content">
                            <pre><code class="language-java">public class RequestLimiter {
    private final Semaphore semaphore;
    private final AtomicInteger completedRequests = new AtomicInteger(0);
    private CountDownLatch completionLatch;
    
    public RequestLimiter(int maxConcurrent) {
        this.semaphore = new Semaphore(maxConcurrent);
    }
    
    public void processRequest(Runnable task) throws InterruptedException {
        semaphore.acquire();
        try {
            task.run();
        } finally {
            semaphore.release();
            completionLatch.countDown();
        }
    }
    
    public void startBatch(int requestCount) {
        this.completionLatch = new CountDownLatch(requestCount);
    }
    
    public void awaitCompletion() throws InterruptedException {
        completionLatch.await();
    }
}</code></pre>
                        </div>
                    </div>
                </div>
            </div>
        </section>

        <!-- Summary Section -->
        <section class="bg-gradient-to-r from-blue-50 to-indigo-50 rounded-2xl p-8 mb-12">
            <div class="text-center">
                <h2 class="text-3xl font-bold mb-6 font-serif">关键要点总结</h2>
                <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
                    <div class="bg-white p-6 rounded-lg shadow-sm">
                        <div class="text-blue-500 text-3xl mb-4">
                            <i class="fas fa-lightbulb"></i>
                        </div>
                        <h3 class="text-lg font-bold mb-2">核心概念</h3>
                        <p class="text-gray-600">CountDownLatch是一个同步辅助类，通过倒计时机制协调多个线程的执行。</p>
                    </div>
                    <div class="bg-white p-6 rounded-lg shadow-sm">
                        <div class="text-blue-500 text-3xl mb-4">
                            <i class="fas fa-check-circle"></i>
                        </div>
                        <h3 class="text-lg font-bold mb-2">最佳实践</h3>
                        <p class="text-gray-600">总是确保countDown()在finally块中调用，考虑使用带超时的await()。</p>
                    </div>
                    <div class="bg-white p-6 rounded-lg shadow-sm">
                        <div class="text-blue-500 text-3xl mb-4">
                            <i class="fas fa-project-diagram"></i>
                        </div>
                        <h3 class="text-lg font-bold mb-2">适用场景</h3>
                        <p class="text-gray-600">并行任务协调、多阶段处理、系统初始化、并发测试等场景。</p>
                    </div>
                </div>
            </div>
        </section>
    </main>

    <!-- Footer -->
    <footer class="bg-gray-900 text-gray-300 py-8">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div class="flex flex-col items-center">
                <div class="text-xl font-bold mb-2">技术小馆</div>
                <div class="mb-4">
                    <a href="http://www.yuque.com/jtostring" class="text-blue-400 hover:text-blue-300 transition-colors">
                        <i class="fas fa-globe mr-1"></i>
                        http://www.yuque.com/jtostring
                    </a>
                </div>
                <div class="text-sm text-gray-500">
                    &copy; 2023 技术小馆. 保留所有权利.
                </div>
            </div>
        </div>
    </footer>

    <script>
        // Initialize Mermaid
        mermaid.initialize({
            startOnLoad: true,
            theme: 'default',
            flowchart: {
                useMaxWidth: false,
                htmlLabels: true,
                curve: 'basis'
            }
        });
        
        // Copy button functionality
        document.querySelectorAll('.code-header button').forEach(button => {
            button.addEventListener('click', () => {
                const code = button.parentElement.nextElementSibling.textContent;
                navigator.clipboard.writeText(code).then(() => {
                    const originalText = button.innerHTML;
                    button.innerHTML = '<i class="fas fa-check mr-1"></i>已复制';
                    setTimeout(() => {
                        button.innerHTML = originalText;
                    }, 2000);
                });
            });
        });
        
        // Smooth scrolling for anchor links
        document.querySelectorAll('a[href^="#"]').forEach(anchor => {
            anchor.addEventListener('click', function(e) {
                e.preventDefault();
                document.querySelector(this.getAttribute('href')).scrollIntoView({
                    behavior: 'smooth'
                });
            });
        });
    </script>
</body>
</html>